package com.lcu.bos.web.action.base;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
    private  T t;//用于接收表单的参数

    //空参方法实现t的实例化
    public BaseAction(){
        //1.获得父类（BaseImpl<T>）的参数化类型
        ParameterizedType genericSuperClass= (ParameterizedType) this.getClass().getGenericSuperclass();
        //2.获取父类的参数化类型的数组
        Type[] types=genericSuperClass.getActualTypeArguments();
        //3.获取泛型类的第一个参数化类型
        Class<T> cls=(Class<T>) types[0];
        try {
            //通过new 创建新的对象
            t=cls.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public void responseJson(String str) throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setHeader("Content-Type","text/html;charset=utf-8");
        response.getWriter().write(str);
    }
    public T getModel() {
        return t;
    }
    //插入数据
    public abstract String save() throws IOException;
    //删除数据
    public abstract String delete() throws IOException;
    //修改用户
    public abstract String update() throws UnsupportedEncodingException;
    //查询数据
    public abstract String get();
    //查询所有数据
    public abstract String findAll();
}
